<template>
  <a-row>
    <a-button type="primary" @click="showDrawer">表格列配置</a-button>
    <slot name="extra"></slot>
    <a-drawer
      placement="right"
      :closable="false"
      :visible="visible"
      :width="1200"
      :mask-closable="true"
      @close="onClose"
    >
      <template #title>
        <span>表格列配置</span>
        <a-button style="float: right" type="primary" @click="onOk"
          >确定</a-button
        >
        <!--        <a-button style="float: right;margin-right: 10px" type="success" @click="onClose">取消</a-button>-->
      </template>
      <variable-selection
        :var-options="varOptions"
        v-if="visible && varVisible"
      ></variable-selection>
      <a-tabs default-active-key="列配置" :position="tabMode">
        <a-tab-pane key="列配置" title="列配置">
          <a-form :model="formData" ref="form">
            <a-button @click="addColumns" type="primary">添加列</a-button>
            <draggable v-model="formData.columns" handle=".mover">
              <a-row
                v-for="(item, index) in formData.columns"
                :key="item.cid"
                :gutter="8"
                type="flex"
                style="align-items: center"
              >
                <a-col :span="1">
                  <a-form-item :label="`第${index + 1}列`" :colon="false">
                    <span class="mover" style="display: inline-flex">拖拽</span>
                  </a-form-item>
                </a-col>
                <a-col :span="3" style="margin-left: 5px">
                  <a-form-item
                    :label="`列名`"
                    :field="`columns.${index}.title`"
                  >
                    <a-input
                      v-model="item.title"
                      placeholder="请输入列名"
                    ></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="3" style="margin-left: 5px">
                  <a-form-item
                    :label="`列名key`"
                    :field="`columns.${index}.title`"
                  >
                    <a-input
                      v-model="item.dataIndex"
                      placeholder="请输入列名key"
                    ></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="3">
                  <a-form-item
                    :label="`列宽`"
                    :field="`columns.${index}.width`"
                  >
                    <a-input-number
                      v-model="item.width"
                      :min="0"
                      style="width: 100%"
                      placeholder="请输入列宽"
                    ></a-input-number>
                  </a-form-item>
                </a-col>
                <a-col :span="3">
                  <a-form-item
                    :label="`类型`"
                    :field="`columns.${index}`"
                    v-if="!item.columnKey"
                  >
                    <a-select
                      v-model="item.controlType"
                      @change="changeControlType($event, item)"
                    >
                      <a-option value="readonly">只读</a-option>
                      <a-option value="input">输入框</a-option>
                      <a-option value="inputNumber">数字输入框</a-option>
                      <a-option value="datePicker">日期选择框</a-option>
                      <a-option value="dataSource">数据源</a-option>
                      <a-option value="upload">上传</a-option>
                      <a-option value="total">计算行数据</a-option>
                      <a-option value="concat">行数据拼接</a-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item
                    :label="`类型`"
                    :field="`columns.${index}`"
                    v-else
                  >
                    <a-select v-model="item.controlType" :disabled="true">
                      <a-option value="sourceKey" v-if="item.columnKey"
                        >数据源展示字段</a-option
                      >
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="4" v-if="item.controlType === 'datePicker'">
                  <a-form-item
                    :label="`日期格式`"
                    :field="`columns.${index}`"
                  >
                    <a-select v-model="item.typeFormat">
                      <a-option value="">请选择</a-option>
                      <a-option value="YYYY-MM">年/月</a-option>
                      <a-option value="YYYY-MM-DD">年/月/日</a-option>
                      <a-option value="YYYY-MM-DD HH:mm:ss"
                        >年/月/日 时分秒</a-option
                      >
                    </a-select>
                  </a-form-item>
                </a-col>
                <!--   数字输入框   -->
                <template v-else-if="item.controlType === 'inputNumber'">
                  <a-col :span="3">
                    <a-form-item
                      :label="`数据类型`"
                      :field="`columns.${index}`"
                    >
                      <a-select
                        v-model="item.dataType"
                        @change="changeDateType($event, item)"
                      >
                        <!--                    <a-option value="">请选择</a-option>-->
                        <a-option
                          v-for="option in numberDataTypeOptions"
                          :key="option.value"
                          :value="option.value"
                        >
                          {{ option.label }}
                        </a-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="3">
                    <a-form-item
                      :label="`数值精度`"
                      :field="`columns.${index}`"
                    >
                      <a-select
                        v-model="item.precision"
                        :disabled="item.dataType === 'int'"
                      >
                        <a-option value="">无限制</a-option>
                        <a-option :value="0" :disabled="true">整数</a-option>
                        <a-option v-for="num in 8" :key="num" :value="num"
                          >保留{{ num }}位小数</a-option
                        >
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col span="4">
                    <a-form-item
                      :label="`统计名称`"
                      :field="`columns.${index}`"
                    >
                      <a-input
                        v-model="item.totalName"
                        placeholder="为空时自动生成"
                      ></a-input>
                    </a-form-item>
                  </a-col>
                  <a-col :span="1">
                    <a-form-item
                      :label="`负数`"
                      :field="`columns.${index}`"
                    >
                      <a-checkbox
                        v-model="item.isNegativeNumber"
                        style="padding-left: 8px"
                      ></a-checkbox>
                    </a-form-item>
                  </a-col>
                  <a-col :span="1">
                    <a-form-item
                      :label="`统计`"
                      :field="`columns.${index}`"
                    >
                      <a-checkbox
                        v-model="item.isStatistics"
                        style="padding-left: 8px"
                      ></a-checkbox>
                    </a-form-item>
                  </a-col>
                </template>
                <!--   数据源配置   -->
                <template
                  v-else-if="
                    item.controlType === 'dataSource' && !item.columnKey
                  "
                >
                  <a-col :span="5">
                    <a-form-item
                      :label="`数据源`"
                      :field="`columns.${index}`"
                    >
                      <a-select
                        v-model="item.dataId"
                        :filter-option="false"
                        @search="queryDatasourceList"
                        show-search
                        @change="queryDataSourceDetails($event, item, index)"
                        allow-clear
                      >
                        <a-option
                          v-for="option in dataSourceList"
                          :key="option.dataId"
                          :value="option.dataId"
                        >
                          <!-- :disabled="formData.columns.some(item => item.dataId === option.dataId)" -->
                          {{ option.dataName }}
                        </a-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <!--            <a-col :span="1"></a-col>-->
                  <a-col :span="5">
                    <a-form-item label="展示字段">
                      <a-select
                        v-model="item.dataShowFields"
                        multiple
                        allow-clear
                      >
                        <a-option
                          v-for="option in dataIdRaw[item.dataId]"
                          :key="option.columnAs"
                          :value="option.columnAs"
                        >
                          {{ option.columnAs }}
                        </a-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="4">
                    <a-form-item label="传值字段">
                      <a-select
                        v-model="item.dataOptionField"
                        allow-clear
                        @change="changeDataOptionField($event, item)"
                      >
                        <a-option
                          v-for="option in dataIdRaw[item.dataId]"
                          :key="option.columnAs"
                          :value="option.columnAs"
                        >
                          {{ option.columnAs }}
                        </a-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col
                    :span="11"
                    v-for="option in item.dataCondition"
                    :key="option.groupId + option.columnKey"
                  >
                    <a-form-item :label="`条件字段：${option.columnKey}`">
                      <!--                  <a-select v-model="option.dataIndex" :allowClear="true" placeholder="请选择映射字段">-->
                      <!--                    <a-option v-for="sItem in [{dataIndex: item.dataOptionField, name: item.dataOptionField}]" :key="sItem.dataIndex" :value="sItem.dataIndex" :disabled="formData.dataCondition.some(e => e.dataIndex === sItem.dataIndex)">{{ sItem.name }}</a-option>-->
                      <!--                  </a-select>-->
                      <a-input
                        v-model="option.defaultTheValue"
                        placeholder="条件默认传参"
                      ></a-input>
                    </a-form-item>
                  </a-col>
                </template>
                <!-- 属于计算行数据的统计和公式  -->
                <template v-if="item.controlType === 'total'">
                  <a-col :span="6">
                    <a-form-item
                      :label="`公式`"
                      :field="`columns.${index}`"
                    >
                      <a-input v-model="item.formula"></a-input>
                    </a-form-item>
                  </a-col>
                  <a-col :span="4">
                    <a-form-item
                      :label="`数值精度`"
                      :field="`columns.${index}`"
                    >
                      <a-select
                        v-model="item.precision"
                        :disabled="item.dataType === 'int'"
                      >
                        <a-option :value="0">整数</a-option>
                        <a-option v-for="num in 8" :key="num" :value="num"
                          >保留{{ num }}位小数</a-option
                        >
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col span="3">
                    <a-form-item
                      :label="`统计名称`"
                      :field="`columns.${index}`"
                    >
                      <a-input
                        v-model="item.totalName"
                        placeholder="为空时自动生成"
                      ></a-input>
                    </a-form-item>
                  </a-col>
                  <a-col :span="1">
                    <a-form-item
                      :label="`统计`"
                      :field="`columns.${index}`"
                    >
                      <a-checkbox
                        v-model="item.isStatistics"
                        style="padding-left: 8px"
                      ></a-checkbox>
                    </a-form-item>
                  </a-col>
                  <a-col :span="1">
                    <a-form-item
                      :label="`隐藏列`"
                      :field="`columns.${index}`"
                    >
                      <a-checkbox
                        v-model="item.hidenColumn"
                        style="padding-left: 8px"
                      ></a-checkbox>
                    </a-form-item>
                  </a-col>
                </template>

                <!-- 行数据拼接配置 -->
                <template v-if="item.controlType === 'concat'">
                  <a-col :span="6">
                    <a-form-item
                      :label="`公式`"
                      :field="`columns.${index}`"
                    >
                      <a-input v-model="item.formula"></a-input>
                    </a-form-item>
                  </a-col>
                </template>

                <a-col :span="6" v-if="item.dataType === 'file'">
                  <a-form-item
                    :label="`文件最大限制`"
                    :field="`columns.${index}`"
                  >
                    <a-input-number
                      :min="0"
                      v-model="item.maxSize"
                      placeholder="单位:MB,0为不限制"
                      style="width: 100%"
                    ></a-input-number>
                  </a-form-item>
                </a-col>
                <a-col :span="1" v-if="item.dataType === 'file'">
                  <a-form-item
                    :label="`下载`"
                    :field="`columns.${index}`"
                  >
                    <a-checkbox
                      v-model="item.allowDownload"
                      style="padding-left: 8px"
                    ></a-checkbox>
                  </a-form-item>
                </a-col>
                <!-- 移动提示语输入框到这里 -->
                <a-col
                  :span="4"
                  v-if="
                    ['input', 'inputNumber', 'datePicker'].includes(
                      item.controlType
                    )
                  "
                >
                  <a-form-item
                    :label="`提示语`"
                    :field="`columns.${index}.placeholder`"
                  >
                    <a-input
                      v-model="item.placeholder"
                      placeholder="请输入提示语"
                    ></a-input>
                  </a-form-item>
                </a-col>
                <a-col
                  :span="3"
                  v-if="['input', 'dataSource'].includes(item.controlType)"
                >
                  <a-form-item label="合并同类项">
                    <a-select v-model="item.mergeType">
                      <a-option value="">无</a-option>
                      <a-option value="asc">合并(升序)</a-option>
                      <a-option value="desc">合并(降序)</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col
                  :span="1"
                  v-if="!['total', 'sourceKey'].includes(item.controlType)"
                >
                  <a-form-item :label="`必填`" :field="`columns.${index}`">
                    <a-checkbox
                      v-model="item.required"
                      style="padding-left: 8px"
                    ></a-checkbox>
                  </a-form-item>
                </a-col>
                <!-- 只读和行数据拼接 隐藏列 -->
                <template
                  v-if="
                    ['readonly', 'concat', 'sourceKey'].includes(
                      item.controlType
                    )
                  "
                >
                  <a-col :span="1">
                    <a-form-item
                      :label="`隐藏列`"
                      :field="`columns.${index}`"
                    >
                      <a-checkbox
                        v-model="item.hidenColumn"
                        style="padding-left: 8px"
                      ></a-checkbox>
                    </a-form-item>
                  </a-col>
                </template>
                <template>
                  <a-col :span="1">
                    <a-form-item :colon="false">
                      <template #label>
                        <span>单隐</span>
                        <a-tooltip placement="top" content="单独查看表格时可选择隐藏列">
                          <span style="margin-left: 4px; vertical-align: middle">?</span>
                        </a-tooltip>
                      </template>
                      <a-checkbox
                        v-model="item.aloneHidenColumn"
                        style="padding-left: 8px"
                      ></a-checkbox>
                    </a-form-item>
                  </a-col>
                </template>
                <a-col>
                  <a-form-item label=" " :colon="false">
                    <a-button type="text" status="danger" @click="removeColumn(item)">删除</a-button>
                  </a-form-item>
                </a-col>
              </a-row>
            </draggable>
          </a-form>
        </a-tab-pane>
        <a-tab-pane key="其它统计" title="其它统计">
          <a-form>
            <a-button
              type="dashed"
              style="margin-bottom: 8px"
              @click="addStatistic"
            >
              添加统计项
            </a-button>
            <div
              v-for="(stat, index) in statisticsConfigs"
              :key="index"
              class="statistic-item"
            >
              <a-row :gutter="8">
                <a-col :span="5">
                  <a-form-item label="统计类型">
                    <a-select
                      v-model="stat.type"
                      @change="handleStatTypeChange($event, stat)"
                    >
                      <a-option value="fixed">固定值</a-option>
                      <a-option value="group">分组统计</a-option>
                      <a-option value="formula">公式计算</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>

                <a-col :span="5" v-if="stat.type !== 'group'">
                  <a-form-item label="显示名称">
                    <a-input
                      v-model="stat.title"
                      placeholder="请输入统计显示名称"
                    />
                  </a-form-item>
                </a-col>

                <!-- 固定值配置 -->
                <template v-if="stat.type === 'fixed'">
                  <a-col :span="5">
                    <a-form-item label="固定值">
                      <a-input v-model="stat.value" style="width: 100%" />
                    </a-form-item>
                  </a-col>
                </template>

                <!-- 分组统计配置 -->
                <template v-if="stat.type === 'group'">
                  <a-col :span="5">
                    <a-form-item label="分组字段">
                      <a-select v-model="stat.field">
                        <a-option
                          v-for="field in varOptions"
                          :key="field.value"
                          :value="field.value"
                        >
                          {{ field.label }}
                        </a-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="5">
                    <a-form-item label="聚合类型">
                      <a-select v-model="stat.aggregateType">
                        <a-option value="sum">求和</a-option>
                        <a-option value="avg">平均值</a-option>
                        <a-option value="max">最大值</a-option>
                        <a-option value="min">最小值</a-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="5">
                    <a-form-item label="每行计算公式">
                      <a-input
                        v-model="stat.formula"
                        placeholder="如: ${amount} * 2"
                        @change="validateFormula($event, stat)"
                      />
                    </a-form-item>
                  </a-col>
                </template>

                <!-- 公式计算配置 -->
                <template v-if="stat.type === 'formula'">
                  <a-col :span="5">
                    <a-form-item label="聚合类型">
                      <a-select v-model="stat.aggregateType">
                        <a-option value="sum">求和</a-option>
                        <a-option value="avg">平均值</a-option>
                        <a-option value="max">最大值</a-option>
                        <a-option value="min">最小值</a-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item label="每行计算公式">
                      <a-input
                        v-model="stat.formula"
                        placeholder="如: ${amount} * 2"
                        @change="validateFormula($event, stat)"
                      />
                    </a-form-item>
                  </a-col>
                </template>

                <a-col :span="1">
                  <a-form-item label=" " :colon="false">
                    <a-button type="text" status="danger" @click="removeStatistic(index)">删除</a-button>
                  </a-form-item>
                </a-col>
              </a-row>
            </div>
          </a-form>
        </a-tab-pane>
      </a-tabs>
    </a-drawer>
  </a-row>
</template>

<script>
// import _ from 'lodash'
// import { nanoid } from 'nanoid'

import { nanoid } from "nanoid";
import VariableSelection from "@/components/Form/Custom/VariableSelection.vue";
import _ from "lodash";

export const numberDataTypeOptions = [
  {
    label: "int",
    value: "int",
  },
  {
    label: "float",
    value: "float",
  },
  {
    label: "double",
    value: "double",
  },
  {
    label: "rate",
    value: "rate",
  },
];
export default {
  name: "TableInfoConfig",
  components: { VariableSelection },
  props: {
    formData: {
      type: Object,
      default: () => ({
        columns: [],
        statisticsConfigs: [], // 修改默认值中的属性名
      }),
    },
  },
  computed: {
    varOptions() {
      return this.formData.columns
        .filter((item) => item.controlType !== "total")
        .map((item) => {
          return {
            value: item.dataIndex,
            label: item.title,
          };
        });
    },
    numberFields() {
      return this.formData.columns
        .filter((col) => ["inputNumber", "total"].includes(col.controlType))
        .map((col) => ({
          value: col.dataIndex,
          label: col.title,
        }));
    },
    // 添加statisticsConfigs的计算属性,处理异常情况
    statisticsConfigs: {
      get() {
        return Array.isArray(this.formData.statisticsConfigs)
          ? this.formData.statisticsConfigs
          : [];
      },
      set(value) {
        // 确保父组件中有statisticsConfigs属性
        if (!this.formData.statisticsConfigs) {
          this.$set(this.formData, "statisticsConfigs", []);
        }
        this.formData.statisticsConfigs = value;
      },
    },
  },
  watch: {
    visible(newVal) {
      setTimeout(() => {
        this.varVisible = newVal; // 给变量按钮一个缓冲显示的时间
      }, 400);
    },
    statisticsConfigs: {
      handler(configs) {
        configs.forEach((stat) => {
          if (stat.type === "group") {
            this.generateGroupTitle(stat);
          }
        });
      },
      deep: true,
    },
  },
  data() {
    return {
      tabMode: "left",
      varVisible: false,
      numberDataTypeOptions,
      dataIdRaw: {}, // 按数据源ID分组选项，用于存储下拉选择项的
      dataShowFieldOptions: [],
      dataSourceList: [], // 数据源列表
      visible: false,
    };
  },
  inject: ["dataObj"],
  methods: {
    /* handleChangeTitle (event, item) {
      const { controlType } = item
      const { dataSource } = this.formData
      if (!(dataSource === 'alone' && ['sourceKey'].includes(controlType))) {
        item.dataIndex = event.target.value
      }
      console.log(item)
    }, */
    changeControlType(type, item) {
      console.log(item);
      if (type === "input") {
        item.dataType = "string";
        item.dataIndex = item.title;
      } else if (type === "inputNumber") {
        item.dataType = "float";
        item.dataIndex = item.title;
      } else if (type === "datePicker") {
        item.typeFormat = "YYYY-MM-DD";
        item.dataType = "timestamp";
        item.dataIndex = item.title;
      } else if (type === "dataSource") {
        item.dataType = "";
      } else if (type === "upload") {
        item.dataType = "file";
      } else if (type === "total") {
        item.dataType = "";
        item.precision = 2;
        item.dataIndex = item.title;
      } else if (type === "concat") {
        item.dataType = "string";
        item.dataIndex = item.title;
        item.formula = "";
      }
    },
    // 传值字段改变
    changeDataOptionField(event, item) {
      const { dataId } = item;
      const data = this.dataIdRaw[dataId].find((e) => e.columnAs === event);
      item.dataType = data?.columnType; // 后端传回的数据类型
      item.typeFormat = data?.typeFormat; // 日期格式
      // item.dataIndex = event // 使用的是别名
    },
    changeDateType(value, item) {
      if (value === "int") {
        item.precision = 0;
      } else if (value) {
        item.precision = 2;
      }
    },
    addColumns() {
      this.formData.columns.push({
        cid: nanoid(10),
        title: "",
        dataIndex: "",
        columnKey: null,
        controlType: "input",
        dataShowFields: [], // 展示字段
        dataOptionField: "", // 传值字段
        dataId: "",
        dataType: "", // 数据类型
        typeFormat: "", // 日期格式
        precision: "", // 数值精度
        isStatistics: false,
        required: false,
        formula: "", // 公式
        totalName: "", // 统计名称
        allowDownload: false, // 是否允许下载
        isNegativeNumber: false,
        hidenColumn: false, // 是否隐藏列
        mergeType: "", // 合并类型
        width: null, // 列宽字段
        placeholder: "", // 新增提示语字段
      });
    },
    removeColumn(item) {
      const index = this.formData.columns.findIndex((e) => e.cid === item.cid);
      const { dataId, controlType } = item;
      if (dataId && controlType === "dataSource") {
        // 代表删除的是根字段，要连带删除数据源返回的字段
        this.formData.columns = this.formData.columns.filter(
          (item) => item.dataId !== dataId
        );
      } else {
        // 有代表删除的是数据源里的字段，直接删
        this.formData.columns.splice(index, 1);
      }
    },
    // 选择了数据源，需要查询有哪些展示字段
    async queryDataSourceDetails(dataId, item, index, mode = "add") {
      try {
        if (!dataId) {
          this.formData.columns = this.formData.columns.filter(
            (e) => e.pCid !== item.cid
          ); // 过滤掉之前数据源生成的数据
          return;
        }
        if (mode === "add" && (index || index === 0)) {
          item.dataShowFields = [];
          item.dataOptionField = "";
        }
        const result = await this.$http.get(
          "/datasource/queryDataSourceDetail",
          {
            params: {
              dataId,
            },
          }
        );
        const { data } = result;
        const { dataColumnQueryDTOList, aggregateFunctionInfoReqDTO } = data;
        const { aggregateFunctionInfoAddDTOList } =
          aggregateFunctionInfoReqDTO || {};
        const mergedList = dataColumnQueryDTOList.concat(
          aggregateFunctionInfoAddDTOList || []
        );
        // 需要根据columnKey去重后的对象数组，而不是单纯的columnKey集合，可以进一步处理：
        this.dataShowFieldOptions = mergedList.filter((item, index, self) => {
          return (
            index === self.findIndex((t) => t.columnKey === item.columnKey)
          );
        });
        _.assign(this.formData.columns[index], {
          dataCondition:
            data.queryGroupReqDTOList
              ?.flatMap((item) => item.tableQueryGroupAddDTOList)
              .map((item) => {
                let oldData = {};
                if (index || index === 0) {
                  // 编辑时，先查找原先的值
                  oldData = this.formData.columns[index].dataCondition?.find(
                    (e) =>
                      e.groupId === item.groupId &&
                      e.columnKey === item.columnKey
                  );
                }
                item.dataIndex = oldData?.dataIndex || null;
                item.defaultTheValue = oldData?.defaultTheValue || "";
                return _.cloneDeep(item);
              }) || [],
        });
        this.dataIdRaw[dataId] = this.dataShowFieldOptions;
        if (mode !== "add") return; // 没有item，代表是编辑进入，不需要过滤

        this.formData.columns = this.formData.columns.filter(
          (e) => e.pCid !== item.cid
        ); // 过滤掉之前数据源生成的数据
        const dataList = [];
        this.dataShowFieldOptions.forEach((showData) => {
          console.log(showData, "数据查看");
          const { columnAs, columnKey, dataId, columnType, typeFormat } =
            showData;
          dataList.push({
            cid: nanoid(10),
            title: columnAs,
            dataIndex: columnAs,
            sourceDataKey: columnAs,
            columnKey: columnKey,
            controlType: "sourceKey",
            dataType: columnType, // 数据类型
            typeFormat,
            dataId: dataId,
            pCid: item.cid,
            allowDownload: false, // 是否允许下载
            mergeType: "",
          });
        });
        this.formData.columns.splice(index + 1, 0, ...dataList);
      } catch (e) {
        console.error("请求失败", e);
      }
    },
    findMatchingQuery(dataCondition, groupId, queryKey) {
      for (const condition of dataCondition) {
        const group = condition.tableQueryGroupAddDTOList;
        if (group) {
          for (const item of group) {
            // 查找具有指定 groupId 和 queryKey 的对象
            if (item.groupId === groupId && item.queryKey === queryKey) {
              return item;
            }
          }
        }
      }

      return null; // 如果没有找到匹配项，则返回 null
    },
    // 查询数据源列表
    async queryDatasourceList(dataName) {
      // try {
      //   const result = await this.$http.post(`/datasource/querySourceAllList`, {
      //     dataTypeList: ["select", "selTable", "interface"],
      //     dataName: dataName || "",
      //   });
      //   const { data } = result;
      //   this.dataSourceList = data;
      // } catch (e) {
      //   console.error("请求失败", e);
      // }
    },
    onOk() {
      // 确保返回的数据中包含新的属性名
      this.$emit("update:formData", {
        ...this.formData,
        statisticsConfigs: this.statisticsConfigs,
      });
      this.visible = false;
    },
    onClose() {
      this.visible = false;
    },
    showDrawer() {
      this.visible = true;
    },
    addStatistic() {
      const newStats = [...this.statisticsConfigs];
      newStats.push({
        type: "formula",
        title: "",
        value: "",
        field: "",
        formula: "",
        aggregateType: "sum", // 默认求和
      });
      this.statisticsConfigs = newStats;
    },
    removeStatistic(index) {
      const newStats = [...this.statisticsConfigs];
      newStats.splice(index, 1);
      this.statisticsConfigs = newStats;
    },
    validateFormula(event, stat) {
      const formula = event.target.value;
      // 检查公式中的变量格式是否正确
      const variables = formula.match(/\${([^}]+)}/g) || [];
      const validFields = this.varOptions.map((opt) => opt.value);

      const invalidVars = variables
        .map((v) => v.slice(2, -1))
        .filter((v) => !validFields.includes(v));

      if (invalidVars.length > 0) {
        this.$message.error(`公式中包含无效的变量: ${invalidVars.join(", ")}`);
        // 可以选择是否要清空无效公式
        // stat.formula = ''
      }
    },
    addAggregate(stat) {
      if (!Array.isArray(stat.aggregates)) {
        this.$set(stat, "aggregates", []);
      }
      stat.aggregates.push({
        field: "",
        type: "sum",
        title: "",
      });
    },
    removeAggregate(stat, index) {
      stat.aggregates.splice(index, 1);
    },
    handleStatTypeChange(type, stat) {
      // 切换类型时重置相关字段
      stat.title = "";
      stat.field = "";
      stat.formula = "";
      stat.value = "";

      // 如果切换到分组统计，设置默认聚合类型为sum
      if (type === "group") {
        stat.aggregateType = "sum";
      } else {
        stat.aggregateType = "";
      }
    },

    // 根据分组字段生成显示名称
    generateGroupTitle(stat) {
      if (stat.type !== "group") return;

      const field = this.varOptions.find((opt) => opt.value === stat.field);
      if (!field) return;

      const aggTypeMap = {
        sum: "求和",
        avg: "平均值",
        max: "最大值",
        min: "最小值",
      };

      // 生成显示名称格式: {字段名称}按{分组字段}分组{聚合类型}
      let title = `${field.label}${aggTypeMap[stat.aggregateType] || ""}`;

      // 如果有计算公式，添加说明
      if (stat.formula) {
        title += "(计算后)";
      }

      stat.title = title;
    },

    // 修改公式计算逻辑
    computeFormula(stat) {
      const data = this.form[this.item.formData.dataIndex] || [];
      const values = data.map((row) => this.evaluateFormula(stat.formula, row));

      // 根据聚合类型计算结果
      switch (stat.aggregateType) {
        case "sum":
          return values.reduce((a, b) => a + b, 0);
        case "avg":
          return values.length
            ? values.reduce((a, b) => a + b, 0) / values.length
            : 0;
        case "max":
          return values.length ? Math.max(...values) : 0;
        case "min":
          return values.length ? Math.min(...values) : 0;
        default:
          return values.reduce((a, b) => a + b, 0);
      }
    },
  },
  created() {
    // 确保初始化时statisticsConfigs存在
    if (!this.formData.statisticsConfigs) {
      this.$set(this.formData, "statisticsConfigs", []);
    }
    this.queryDatasourceList();
    this.formData.columns.forEach((item, index) => {
      this.queryDataSourceDetails(item.dataId, item, index, "edit");
    });
  },
};
</script>

<style lang="less" scoped>
.statistic-item {
  background: #fafafa;
  padding: 16px;
  margin-bottom: 16px;
  border: 1px dashed #d9d9d9;
  border-radius: 2px;
}
</style>
